package com.gy.algorithm.carl.linklistexa;

import java.util.List;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl.linklistexa
 * @Author: gy
 * @Date: 2024/10/24 19:25
 * @Description:
 */
public class Prac_AddTwoNumbers1 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode res = dummy;

        ListNode pre = l1;
        ListNode next = l2;

        int extra = 0;
        int sum = 0;

        while(pre != null || next != null){
            ListNode tmp = new ListNode();

            if(extra != -1) sum += extra;

            if(pre != null){
                sum += pre.val;
                pre = pre.next;
            }

            if(next != null){
                sum += next.val;
                next = next.next;
            }

            tmp.val = sum % 10;
            extra = sum / 10;
            sum = 0;

            dummy.next = tmp;
            dummy = dummy.next;
        }

        if(extra != 0){
            dummy.next = new ListNode(extra);
        }

        return res.next;
    }
}
